//
//  HttpRequsetViewController.m
//  BaseTools
//
//  Created by 李挺哲 on 15/8/24.
//  Copyright (c) 2015年 ltz. All rights reserved.
//
#import "HttpClient.h"
#import "HttpRequsetViewController.h"
#import "MJRefresh.h"
#import "News.h"
#import "NewsTableViewCell.h"
#import "WebViewViewController.h"
@interface HttpRequsetViewController ()
@property(strong,nonatomic)NSMutableArray *data;
@property(assign,nonatomic)int pageSize;
@property(assign,nonatomic)int pageNow;

@end

@implementation HttpRequsetViewController

- (void)loadNewData {
    
    NSArray *document=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *dicpath=document[0];
    
    NSString *filePath=[dicpath stringByAppendingPathComponent:@"dic.plist"];
    [self showIndicatorView:kNetworkConnecting];
    NSString *url=@"http://api.huceo.com/huabian/";
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [ parameters setValue:@"5c1b6939d3b5c7f9286e74b4bbeea009" forKey:@"key"];
    [ parameters setValue:[NSString stringWithFormat:@"%d",_pageSize] forKey:@"num"];
    [ parameters setValue:[NSString stringWithFormat:@"%d",_pageNow]forKey:@"page"];
    
    [HttpClient JSONDataWithUrl:url parameters:parameters success:^(id json) {
        [self dismissIndicatorView];
        
//        NSLog(@"%@",json);
        NSData *data= [json dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dictionary=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

        [dictionary writeToFile:filePath atomically:YES];
        
        [_data removeAllObjects];
        for (int i=0; i<dictionary.count-2; i++) {
            
            News *news=[[News alloc] initWithDict:dictionary[[NSString stringWithFormat:@"%d",i]]];
            [_data addObject:news];
        }
        
        [_tableView reloadData];
        [_tableView.header endRefreshing];
        NSLog(@"count  %lu",(unsigned long)_data.count);
        
    } fail:^{
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNavigationTitle:@"HTTP请求+图片异步加载" barTintColor:0x1E86CB titleColor:0xFFFFFF isTranslucent:NO isHidden:NO];
    [self showNavigationLeftButtonTitle:@"返回" tintColor:0xFFFFFF];
    _data=[NSMutableArray array];
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    // 设置了底部inset
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 30, 0);
    // 忽略掉底部inset
    self.tableView.footer.ignoredScrollViewContentInsetBottom = 30;
    _pageNow=1;
    _pageSize=11;
    _data=[NSMutableArray array];
    [self loadNewData];
    
    
    
    
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    
    NewsTableViewCell * cell=[NewsTableViewCell newsTableViewCellWithTableView:tableView];
  News *news=  _data[indexPath.row];
    [cell setData:news];
    return cell;
}

-(void)loadMoreData{
    _pageNow++;
    NSString *url=@"http://api.huceo.com/huabian/";
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [ parameters setValue:@"5c1b6939d3b5c7f9286e74b4bbeea009" forKey:@"key"];
    [ parameters setValue:[NSString stringWithFormat:@"%d",_pageSize] forKey:@"num"];
    [ parameters setValue:[NSString stringWithFormat:@"%d",_pageNow]forKey:@"page"];
    [self showIndicatorView:kNetworkConnecting];
    [HttpClient JSONDataWithUrl:url parameters:parameters success:^(id json) {
        
        [self dismissIndicatorView];
        NSData *data= [json dataUsingEncoding:NSUTF8StringEncoding];
        
        NSLog(@"%@",json);
        NSDictionary *dictionary=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSMutableArray *array=[NSMutableArray array];
        
        
        for (int i=0; i<dictionary.count-2; i++) {
            
            News *news=[[News alloc] initWithDict:dictionary[[NSString stringWithFormat:@"%d",i]]];
            [array addObject:news];
        }
        [_data addObjectsFromArray:array];
        
        [_tableView reloadData];
        [_tableView.footer endRefreshing];
        NSLog(@"count  %lu",(unsigned long)_data.count);

        
    } fail:^{
        
    }];

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    WebViewViewController *webViewController= [self.storyboard instantiateViewControllerWithIdentifier:@"WebViewViewController"];
     News *news=  _data[indexPath.row];
    webViewController.url=news.url;
    [self.navigationController showViewController:webViewController sender:self ];

}

@end
